package org.example.pims.security.service;

import org.example.pims.security.LoginUser;
import org.example.commons.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @author bothin
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

   /* @Resource
    private AuthenticationManager authenticationManager;*/

    @Autowired
    private AdminUserDetailsServiceImpl adminUserDetailsService;

    @Autowired
    private UserUserDetailsServiceImpl userUserDetailsService;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            LoginAuthenticationProvider provider = new LoginAuthenticationProvider(adminUserDetailsService);
            authentication = provider
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            throw new CustomException(e.getMessage());

        }
        if (authentication == null)
            throw new CustomException("账号或密码错误，请检查一下");

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public String userLogin(String username, String password) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            LoginAuthenticationProvider provider = new LoginAuthenticationProvider(userUserDetailsService);
            authentication = provider
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            throw new CustomException(e.getMessage());

        }
        if (authentication == null)
            throw new CustomException("账号或者密码错误");
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
